package com.geekaca.jsp;

import com.geekaca.jsp.pojo.Brand;
import com.geekaca.jsp.pojo.BrandType;
import com.geekaca.jsp.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/updateBrand")
public class UpdateBrandServlet extends HttpServlet {
    private BrandService brandService = new BrandService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       /* // 登录确认
        HttpSession session = req.getSession();
        Object loggedObj = session.getAttribute("logged");

        System.out.println("loggedobj: " + loggedObj);
        String logged = loggedObj.toString();
        System.out.println("logged: " + logged);

        if (!logged.equals("1")) {
            resp.setHeader("Content-type", "text/html; charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write("<h1>非法请求，请先登录</h1>");
            return;
        }*/

        // 更新
        req.setCharacterEncoding("utf-8");
        System.out.println("updatebrand servlet...");
        String idstr = req.getParameter("id");
        Integer id = Integer.parseInt(idstr);

        String brandName = req.getParameter("brandName");
        String companyName = req.getParameter("companyName");

        String orderedstr = req.getParameter("ordered");
        Integer ordered = Integer.parseInt(orderedstr);

        String brandTypeName = req.getParameter("brandType");
        Integer type_id = Integer.valueOf(brandTypeName);


        String description = req.getParameter("description");

        String statusstr = req.getParameter("status");
        Integer status = Integer.parseInt(statusstr);

        BrandType brandType;

        switch (type_id) {
            case 1:
                brandType = new BrandType(1, 1, "食品");
                break;
            case 2:
                brandType = new BrandType(2, 2, "数码");
                break;
            case 3:
                brandType = new BrandType(3, 3, "文化");
                break;
            default:
                brandType = new BrandType();
        }


        Brand brand = new Brand(id,brandName,companyName,ordered,description,status,brandType);


        int updated = brandService.updateBrand(brand);
        if (updated > 0) {
            // 跳转到展示页面
            req.getRequestDispatcher("/brands").forward(req, resp);
        } else {
            PrintWriter writer = resp.getWriter();
            writer.write("<h2>更新错误！</h2>");
        }


    }
}
